package primalgorithms.string;

public class _06StringToInt {

    //写个这东西真不容易啊，到处改错，增补，最后效率也一般般
    public static int myAtoi(String s) {
        if(s.length() == 0){
            return 0;
        }
        s = s.trim();
        if(s.length() == 0){
            return 0;
        }
        if(s.length() == 1){
            return Character.isDigit(s.charAt(0)) ? Integer.parseInt(Character.toString(s.charAt(0))) : 0;
        }
        if(!Character.isDigit(s.charAt(0))){
            if(s.charAt(0)!='+' && s.charAt(0)!='-'){
                return 0;
            }
            if(!Character.isDigit(s.charAt(1))){
                return 0;
            }
        }
        if(Character.isDigit(s.charAt(0))){
            for (int i = 0;i < s.length();i++){
                if(!Character.isDigit(s.charAt(i))){
                    s = s.substring(0,i);
                }
            }
        }else {
            for (int i = 1; i < s.length(); i++) {
                if (!Character.isDigit(s.charAt(i))) {
                    s = s.substring(0,i);
                }
            }
        }

        try {
            return Integer.parseInt(s);
        }catch (Exception e){
            if(s.charAt(0)=='-') {
                return Integer.MIN_VALUE;
            }else {
                return Integer.MAX_VALUE;
            }
        }
    }
}
